package com.mzj.saas.mservice.sms.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class CodeService {

	private static final Logger LOG = LoggerFactory.getLogger(CodeService.class);
	@Autowired
	@Qualifier("stringRedisTemplate")
	private StringRedisTemplate redisTemplate;
	
	/**
	 * 默认code长度
	 */
	private static final int DEFAULT_CODE_LENGTH = 6;
	/**
	 * code长度key
	 */
	private static final String CODE_LENGTH_KEY = "CODE_LENGTH_KEY";
	/**
	 * code数字的key
	 */
	private static final String CODE_VALUE_KEY = "CODE_VALUE_KEY";
	public String getCode(){
		Random r = new Random();
		int addNum = r.nextInt(15)+3;
		long num = redisTemplate.opsForValue().increment(CODE_VALUE_KEY, addNum);
		int codeLength = getCodeLength();
		long total = (long)Math.pow(10, codeLength);
		long codeNum = num%total;	
		return  getStr(codeNum, codeLength);
		
	}
	
	private String getStr(long i, int length) {
		
		int zeroLength = 0;
		String result = ""; 
		for (int j = 1; j < length; j++) {
			if(i%Math.pow(10, j)==i){
				zeroLength = length-j;
				break;
			}
		}
		for (int j = 0; j <zeroLength; j++) {
			result+="0";
		}
		result+=i;
		return result;
	}
	
	
	/**
	 * 获取code长度
	 * @return
	 */
	public int getCodeLength() {
		int codeLenth = DEFAULT_CODE_LENGTH;
		if(redisTemplate.hasKey(CODE_LENGTH_KEY)){
			String length=redisTemplate.opsForValue().get(CODE_LENGTH_KEY);
			try {
				codeLenth = Integer.parseInt(length);
			} catch (Exception e) {
				LOG.error(e.getMessage(), e);
			}
			if(codeLenth<=0){
				codeLenth = DEFAULT_CODE_LENGTH;
			}
		}
		return codeLenth;
	}

}
